import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;


public class MessageListener extends Thread {
	private int port;
		
	private DatagramSocket socket;
	
	public MessageListener(int port){
		
		try{
			this.port=port;				
			socket=new DatagramSocket(this.port);
		}catch(SocketException e){
			System.out.println("Cannot listen on port " + this.port);
			e.printStackTrace();
		}		
	}
	
	public void run(){		
		System.out.println("MessageListener listens at port " + this.port);
		while(true){ //Continuously listen on the given port
			byte[] buf = new byte[256];
			DatagramPacket packet = new DatagramPacket(buf, buf.length);
			
			try{
								
				socket.receive(packet); //This is the blocking method. So it is run inside the Thread.run() method.
				byte[] byteMsg=packet.getData();				
			
				Message msg=new Message(byteMsg);
								
				//System.out.println("Server receive the following message at " + java.util.Calendar.getInstance().getTime().toString());
				System.out.println(msg.toString());
				Thread.sleep(10);
			}catch(IOException e){ //for socket.receive
				e.printStackTrace();
				socket.close();
				break;
			}catch(InterruptedException e){ //for Thread.sleep
				e.printStackTrace();
				socket.close();
				break;
			}
		}
	}
	
	

}